package com.ocom.payhandle.controller;

import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.card.EntityCardInfo;
import com.ocom.common.entity.card.EntityXfAccountInfo;
import com.ocom.common.entity.card.EntityXfRecord;
import com.ocom.common.entity.card.EntityXfSubAccountList;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.MachEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.payhandle.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
public class XFPayController {

    private static Logger log = LoggerFactory.getLogger(XFPayController.class);

    @Autowired
    private XfCardInfoService xfCardInfoService;

    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private RoommateInfoService roommateInfoService;

    @Autowired
    private XfSubAccountListService xfSubAccountListService;

    @Autowired
    private VoucherDataService voucherDataService;

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    /*
     * @Description: 余额查询
     * @Author: lu
     * @Date: 2022/6/29 15:14
     * @param jsonObject:
     * @return: com.ocom.common.resp.RespMachMessage
     **/
    @PostMapping(value = PayHandleUrl.URL_getBalance)
    public RespMachMessage getBalance(@RequestBody JSONObject jsonObject){
        log.info("查询余额请求参数，【{}】",jsonObject);
        try {
            if (jsonObject.getInteger("companyID")==null || jsonObject.getInteger("type")==null
                    || StringUtils.isEmpty(jsonObject.getString("cardNum"))){
                return RespUtilMach.error(MachEnum.REQUIRED_NULL);
            }
            Map<String,Object> map=new HashMap<>();
            Map<String,Object> accountInfMap=new HashMap<>();
            Integer pId=0;
            //1-物理卡号，3-员工ID，4-人脸ID
            //1.判断type,根据type值选择获取余额方式：
            //(1)type=1时需通过卡信息表获取卡账号，再通过卡账号在消费账号表中获取余额信息与p_id;
            EntityXfAccountInfo entityXfAccountInfo=null;
            if (jsonObject.getInteger("type")==1){
                EntityCardInfo entityCardInfo=xfCardInfoService.selectAccountNos(jsonObject.getLong("companyID"),jsonObject.getString("cardNum"));
                if (entityCardInfo==null){
                    return RespUtilMach.error(MachEnum.CARDSTATERR);
                }
                entityXfAccountInfo=xfAccountInfoService.selectAccountNoBalance(jsonObject.getLong("companyID"),entityCardInfo.getAccountNo());
                if(entityXfAccountInfo!=null) pId= Math.toIntExact(entityXfAccountInfo.getPId());
            }else if (jsonObject.getInteger("type")==3 || jsonObject.getInteger("type")==4){
                pId= Integer.valueOf(jsonObject.getString("cardNum"));
                entityXfAccountInfo=xfAccountInfoService.selectPIdBalance(jsonObject.getLong("companyID"),pId);
            }else {
                return RespUtilMach.error(MachEnum.PAYTYPEERR);
            }
            if (entityXfAccountInfo==null){
                return RespUtilMach.error(MachEnum.ACCOUNT);
            }
            EntityPersonnelInfo entityPersonnelInfo=personnelInfoService.selectPerInfoName(jsonObject.getLong("companyID"),pId);
            if (entityPersonnelInfo==null){
                return RespUtilMach.error(MachEnum.USER_NOT_FIND);
            }
            accountInfMap.put("money",entityXfAccountInfo.getAccountRechargeMoney());
            accountInfMap.put("allowance",entityXfAccountInfo.getAccountSubsidyMoney());
            accountInfMap.put("name",entityPersonnelInfo.getPName());
            map.put("type",jsonObject.getInteger("type"));
            map.put("cardNum",jsonObject.getString("cardNum"));
            map.put("accountType",1);
            map.put("balckFlag",0);
            map.put("concardFlag",0);
            map.put("cardNoFlag",0);
            map.put("accountInf",accountInfMap);
            map.put("pId",pId);
            return RespUtilMach.success(map);
        }catch (Exception e){
            log.info("余额查询，e:"+e);
            return RespUtilMach.error(MachEnum.ERR);
        }

    }


    @PostMapping(PayHandleUrl.URL_verifyPassword)
    public Result verifyPassword(Long companyId, Long pId, String password){
        if (companyId ==null || pId ==null || password ==null){
            return ResultUtil.error(ResultEnum.Err_203);
        }
        try {
//            String key = MD5.MD5Encode(companyId.toString(), "utf8");
            EntityPersonnelInfo entityPersonnelInfo=personnelInfoService.verifyPassword(companyId,pId);
            if (entityPersonnelInfo != null) {
//                String passwords= AES.decrypt(entityPersonnelInfo.getEncryPhone(),key);
//                String phone=passwords.substring(passwords.length() - 4);
                if (entityPersonnelInfo.getPPhone().equals(password)){
                    Map<String,Object> map=new HashMap<>();
                    map.put("flag",0);
                    return ResultUtil.success(map);
                }
            }
        }catch (Exception exception){
            log.error("验证个人密码:{{}}",exception.getMessage());
        }
        return ResultUtil.error(ResultEnum.Err_2003);
    }


    //
    @PostMapping(PayHandleUrl.URL_getCardInfo)
    public Result getCardInfo(Long companyId,String cardNo){
        EntityCardInfo entityCardInfo = xfCardInfoService.selectCard(companyId,cardNo);
        if(entityCardInfo==null){
            return ResultUtil.error(ResultEnum.Err_4021);
        }
        return ResultUtil.success(entityCardInfo);
    }


    @PostMapping(value = PayHandleUrl.URL_getBalancePhone)
    public RespMachMessage getBalancePhone(@RequestBody JSONObject jsonObject){
        log.info("查询余额请求参数，【{}】",jsonObject);
        try {
            if (jsonObject.getInteger("companyID")==null || jsonObject.getInteger("type")==null
                    || StringUtils.isEmpty(jsonObject.getString("cardNum"))){
                return RespUtilMach.error(MachEnum.REQUIRED_NULL);
            }
            Map<String,Object> map=new HashMap<>();
            Map<String,Object> accountInfMap=new HashMap<>();
            Integer pId=0;
            //1-物理卡号，3-员工ID，4-人脸ID
            //1.判断type,根据type值选择获取余额方式：
            //(1)type=1时需通过卡信息表获取卡账号，再通过卡账号在消费账号表中获取余额信息与p_id;
            EntityXfSubAccountList entityXfSubAccountList = null;
            if (jsonObject.getInteger("type")==1){
                EntityCardInfo entityCardInfo=xfCardInfoService.selectAccountNos(jsonObject.getLong("companyID"),jsonObject.getString("cardNum"));
                if (entityCardInfo==null){
                    return RespUtilMach.error(MachEnum.CARDSTATERR);
                }
                entityXfSubAccountList = xfSubAccountListService.getUserSubAccount(
                        jsonObject.getLong("companyID"),
                        entityCardInfo.getPId(),
                        1
                );
                pId= Math.toIntExact(entityCardInfo.getPId().intValue());
            }else if (jsonObject.getInteger("type")==3 || jsonObject.getInteger("type")==4){
                pId= Integer.valueOf(jsonObject.getString("cardNum"));
                entityXfSubAccountList = xfSubAccountListService.getUserSubAccount(
                        jsonObject.getLong("companyID"),
                        pId.longValue(),
                        1
                );
            }else {
                return RespUtilMach.error(MachEnum.PAYTYPEERR);
            }
            if (entityXfSubAccountList==null){
                return RespUtilMach.error(MachEnum.ACCOUNT);
            }
            EntityPersonnelInfo entityPersonnelInfo=personnelInfoService.selectPerInfoName(jsonObject.getLong("companyID"),pId);
            if (entityPersonnelInfo==null){
                return RespUtilMach.error(MachEnum.USER_NOT_FIND);
            }
            accountInfMap.put("money",entityXfSubAccountList.getAccountRechargeMoney());
            accountInfMap.put("allowance",entityXfSubAccountList.getAccountSubsidyMoney());
            accountInfMap.put("name",entityPersonnelInfo.getPName());
            map.put("type",jsonObject.getInteger("type"));
            map.put("cardNum",jsonObject.getString("cardNum"));
            map.put("accountType",1);
            map.put("balckFlag",0);
            map.put("concardFlag",0);
            map.put("cardNoFlag",0);
            map.put("accountInf",accountInfMap);
            map.put("package",voucherDataService.selectVoucherList(jsonObject.getLong("companyID"),pId.longValue(),new Date()));
            //新增
            map.put("familyInf",roommateInfoService.getRoomPerson(jsonObject.getLong("companyID"),pId.longValue()));
            //获取联系人
            log.info("获取联系人信息 【{}】",map);
            return RespUtilMach.success(map);
        }catch (Exception e){
            log.info("余额查询，e:"+e);
            return RespUtilMach.error(MachEnum.ERR);
        }

    }


    @PostMapping(value = PayHandleUrl.URL_updateXfFace)
    public RespMachMessage updateXfFace(@RequestBody EntityXfRecord entityXfRecord){
//        log.info("更新人脸 【{}】【{}】【{}】",entityXfRecord.getDeviceNo(),entityXfRecord.getOrderNo(),entityXfRecord);
        if(CommonUtil.isNull(entityXfRecord.getDeviceNo())
        || CommonUtil.isNull(entityXfRecord.getOrderNo())){
            return RespUtilMach.success();
        }
        xfRecordProcessService.updateXfFace(entityXfRecord.getComId(),entityXfRecord);
        return RespUtilMach.success();
    }


}
